Skip to content

Method: static {...}

1: /*
2: * Copyright © 2021-2023 Fachhochschule für die Wirtschaft (FHDW) Hannover
3: *
4: * This file is part of ipspiel24-demo.
5: *
6: * Ipspiel24-demo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
7: * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
8: * version.
9: *
10: * Ipspiel24-demo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
11: * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12: *
13: * You should have received a copy of the GNU General Public License along with ipspiel24-demo. If not, see
14: * <http://www.gnu.org/licenses/>.
15: */
16: package de.fhdw.gaming.ipspiel24.tictactoe.core.domain.impl;
17:
18: import java.util.ArrayList;
19: import java.util.List;
20: import java.util.Optional;
21: import java.util.Random;
22:
23: import de.fhdw.gaming.ipspiel24.tictactoe.core.domain.TicTacToeField;
24: import de.fhdw.gaming.ipspiel24.tictactoe.core.domain.TicTacToeFieldState;
25: import de.fhdw.gaming.ipspiel24.tictactoe.core.domain.TicTacToeMoveGenerator;
26: import de.fhdw.gaming.ipspiel24.tictactoe.core.domain.TicTacToePlayer;
27: import de.fhdw.gaming.ipspiel24.tictactoe.core.domain.TicTacToeState;
28: import de.fhdw.gaming.ipspiel24.tictactoe.core.moves.TicTacToeMove;
29: import de.fhdw.gaming.ipspiel24.tictactoe.core.moves.factory.TicTacToeMoveFactory;
30: import de.fhdw.gaming.ipspiel24.tictactoe.core.moves.impl.TicTacToeDefaultMoveFactory;
31:
32: /**
33: * Implements the {@link TicTacToeMoveGenerator} interface.
34: */
35: final class TicTacToeMoveGeneratorImpl implements TicTacToeMoveGenerator {
36:
37: /**
38: * The random number generator.
39: */
40: private static final Random RANDOM = new Random();
41:
42: /**
43: * The move factory.
44: */
45: private final TicTacToeMoveFactory moveFactory = new TicTacToeDefaultMoveFactory();
46:
47: @Override
48: public Optional<TicTacToeMove> generate(final TicTacToePlayer player, final TicTacToeState state) {
49: final List<TicTacToeField> fields = new ArrayList<>(
50: state.getBoard().getFieldsBeing(TicTacToeFieldState.EMPTY).values());
51:
52: if (fields.isEmpty()) {
53: return Optional.empty();
54: }
55: final int index = RANDOM.nextInt(fields.size());
56: final TicTacToeField field = fields.get(index);
57: return Optional.of(this.moveFactory.createPlaceMarkMove(player.isUsingCrosses(), field.getPosition()));
58: }
59: }